﻿using System;
using System.Net;
using System.Reflection;
using System.Xml;

namespace UploadClient.Utilitys
{
    public class LatestVersionChecker
    {




        public LatestVersionChecker()
        {

        }
        /// <summary>
        /// Returns true if there is a upgrade available 
        /// </summary>
        /// <returns></returns>
        public bool CheckLatestVersionPresent()
        {

            //Check for latest version 
            bool bIsServerVersionGreater = false;

            try
            {
                Version currVer = GetCurrentVersion();

                string versionFromServer = GetVersionFromServer();

                if (!string.IsNullOrEmpty(versionFromServer))
                {
                    Version version = new Version(versionFromServer);

                    bIsServerVersionGreater = version > currVer;
                }

            }
            catch (Exception ex)
            {
                //Do not do any thing
                //If the download of updates file has failed 
                //The the upgrade will be checked next time

            }
            return bIsServerVersionGreater;

        }

        private string GetVersionFromServer()
        {

            string sVersionFromServer = string.Empty;

            using (WebClient client = new WebClient())
            {

                client.DownloadFile("https://ftpuploadclient.svn.codeplex.com/svn/Client/FtpClient/Releases/Updates.xml", "Updates.xml");

            }
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load("Updates.xml");

            XmlNode node = xmlDoc.SelectSingleNode("//FtpUploadClient//Update");
            XmlAttribute attr = node.Attributes["Version"];

            sVersionFromServer = attr.Value;


            return sVersionFromServer;


        }

        private Version GetCurrentVersion()
        {
            string sVersion = string.Empty;

            Assembly currAssembly = Assembly.LoadFrom("FTPUploadClient.exe");

            return currAssembly.GetName().Version;

        }
    }
}
